<template>
  <div id="rptResultBac">
    <vxe-toolbar class-name="bg-grey light">
      <template #buttons>
        <span v-for="(item, index) in labmaininfobacbtns" :key="index" class="padding-lr-xs">
          <vxe-button v-if="item.type === 0" type="text" class="button-blue" :icon="item.icon" :content="item.content" @click="actionEvent(item)"></vxe-button>
          <vxe-button v-if="item.type === 101" :disabled="labMainInfoObj.isChk == 2" type="text" class="button-blue" :icon="item.icon" :content="item.content" @click="actionEvent(item)"></vxe-button>
          <span v-if="item.type === 1">
            <vxe-button v-for="(val, idx) in item.children" :key="idx" type="text" class="button-blue" :icon="val.position === 'left' ? val.icon : ''" @click="actionCLick(val)">
              {{ val.content }}
              <i v-if="val.position === 'right'" :class="val.icon"></i>
            </vxe-button>
          </span>
          <vxe-button v-if="!isVisiableFChkBtn && item.type === 3 && item.name && item.name === 'firstReviewed' && (labMainInfoObj.isChk < 1 || labMainInfoObj.isChk === null)" type="text" class="button-blue" content="初审"></vxe-button>
          <vxe-button v-if="!isVisiableFChkBtn && item.type === 3 && item.name && item.name === 'firstReviewed' && labMainInfoObj.isChk == 1" type="text" class="button-red" content="取消初审"></vxe-button>
          <vxe-button v-if="item.type === 3 && item.name && item.name === 'reviewed' && (labMainInfoObj.isChk < 2 || labMainInfoObj.isChk === null)" type="text" class="button-blue" content="审核" @click="actionCLick(item.children[0])"></vxe-button>
          <vxe-button v-if="item.type === 3 && item.name && item.name === 'reviewed' && labMainInfoObj.isChk == 2" type="text" class="button-red" content="取消审核" @click="actionCLick(item.children[1])"></vxe-button>
          <vxe-button v-if="item.type === 5 && dzblBtnText !== ''" type="text" class="button-blue" :icon="item.icon" :content="dzblBtnText" @click="actionCLick(item)"></vxe-button>
        </span>
      </template>
    </vxe-toolbar>
    <el-tabs v-model="activeName" type="card" class="lab-bac-test-result-tab el-tab-sm" @tab-click="tabHandleClick">
      <el-tab-pane label="细菌报告" name="first"></el-tab-pane>
      <el-tab-pane label="过程记录" name="second">过程记录</el-tab-pane>
      <el-tab-pane label="流程单" name="third">流程单</el-tab-pane>
      <el-tab-pane label="申请项目" name="fourth"></el-tab-pane>
      <el-tab-pane label="费用补录" name="five"></el-tab-pane>
    </el-tabs>
    <Splitpanes horizontal v-if="activeName === 'first'" class="bacRptResult-splitpanes" :dbl-click-splitter="false">
      <Pane :size="paneTopSize">
        <Splitpanes :dbl-click-splitter="false">
          <Pane :size="bacPanelSize" :max-size="bacPanelSize" :min-size="bacPanelSize">
            <div style="height: calc(100%)">
              <el-scrollbar height="100%">
                <div class="padding-sm bac-card line-gray solid-left">
                  <div v-for="(m, i) in rptResultBac" :key="i">
                    <el-card :style="{ maxWidth: '100%' }" class="margin-bottom-xs" :class="i === curSelectBacResultIndex ? 'bg-green light' : ''" @click="bacResultCardClick(m, i)">
                      <template #header>
                        <div class="flex justify-between" style="width: 100%">
                          <div class="flex justify-start" style="width: 90%">
                            <span class="margin-right-xs">{{ m.isolateNum }}</span>
                            <span class="text-cut" style="width: 90%; max-width: 90%">{{ `${m.germNo ? m.germNo : ''}` }}</span>
                          </div>
                          <span class="vxe-icon-edit padding-left-xs" @click="bacTestResultEditClick(m, i)"></span>
                        </div>
                      </template>
                      <div class="bac-result-content">
                        <div class="flex justify-start">
                          <span class="label-des">结果:</span><span style="width: calc(100% - 30px)" class="text-bold"> {{ m.germNa }}</span>
                        </div>
                        <div class="flex justify-start" v-if="m.urinColoCount">
                          <span class="label-des">菌落计数:</span><span class="text-cut" style="width: 65%"> {{ m.urinColoCount }}</span>
                        </div>
                        <div class="flex justify-start" v-if="m.testResult">
                          <span class="label-des">结果描述:</span><span class="text-cut" style="width: 65%">{{ m.testResult }}</span>
                        </div>
                        <div class="flex justify-start" v-if="m.infeSiteNa">
                          <span class="label-des">感染部位:</span><span class="text-cut">{{ m.infeSiteNa }}</span>
                        </div>
                        <div class="flex justify-start" v-if="m.bacRate">
                          <span class="label-des">菌群占比:</span><span class="text-cut">{{ m.bacRate }}%</span>
                        </div>
                        <div class="flex justify-start">
                          <span class="label-des" v-if="m.resiPhenNa">耐药表型:</span><span v-if="m.resiPhenNa" class="text-cut" style="width: 65%">{{ m.resiPhenNa }}</span>
                        </div>
                        <div class="flex justify-start">
                          <span class="label-des" v-if="m.isAlarm">是否危急值:</span><span v-if="m.isAlarm" class="text-cut" style="width: 65%">{{ m.isAlarm }}</span>
                        </div>
                      </div>
                      <template #footer>
                        <div class="flex justify-between">
                          <div>
                            <el-popover v-if="m.isAlarm == '1'" size="small" placement="right-end" title="危急值描述" effect="dark" :width="200" trigger="hover" popper-style="font-size: 0.8em;" :content="m.alarmText">
                              <template #reference>
                                <el-button type="danger" size="small" circle v-if="m.isAlarm == '1'">危</el-button>
                              </template>
                            </el-popover>
                            <el-popover v-if="!IsEmpty(m.testResult)" size="small" placement="right-end" title="结果描述" effect="dark" :width="200" trigger="hover" popper-style="font-size: 0.8em;" :content="m.testResult">
                              <template #reference>
                                <el-button type="success" size="small" circle v-if="i === curSelectBacResultIndex">结</el-button>
                                <el-button size="small" circle v-else>结</el-button>
                              </template>
                            </el-popover>
                            <el-popover v-if="!IsEmpty(m.descText)" size="small" placement="right-end" title="专家评语" effect="dark" :width="200" trigger="hover" popper-style="font-size: 0.8em;" :content="m.descText">
                              <template #reference>
                                <el-button type="success" size="small" circle v-if="i === curSelectBacResultIndex">专</el-button>
                                <el-button size="small" circle v-else>专</el-button>
                              </template>
                            </el-popover>
                          </div>
                          <span class="vxe-icon-delete-fill text-gray" @click="bacTestResultDeleteClick(m, i)" style="margin-top: 5px" v-show="labMainInfoObj.isChk != '2'"></span>
                        </div>
                      </template>
                    </el-card>
                  </div>
                </div>
              </el-scrollbar>
            </div>
          </Pane>
          <Pane :size="drugPanelSize">
            <vxe-toolbar>
              <template #buttons>
                <span class="text-bold margin-left-xs">抗生素结果</span>
              </template>
              <template #tools>
                <span class="text-bold margin-lr-xs">自动计算</span>
                <vxe-switch v-model="form.autocalc"></vxe-switch>
                <vxe-button type="text" class="button-blue margin-lr-xs" class-name="margin-lr-xs" content="刷新" @click="bacDrugTestResultRefresh"></vxe-button>
                <vxe-button type="text" class="button-blue margin-lr-xs" class-name="margin-lr-xs" content="新增抗生素" @click="insertBacDrugTestResult" :disabled="resultIsDisabled()"></vxe-button>
                <vxe-button type="text" class="button-blue margin-lr-xs" class-name="margin-lr-xs" content="新增药敏组" @click="insertBacDrugResultTemplate" :disabled="resultIsDisabled()"></vxe-button>
                <!-- <vxe-button type="text" class="button-blue margin-lr-xs" class-name="margin-lr-xs" content="设置折点" :disabled="resultIsDisabled()"></vxe-button> -->
                <vxe-button type="text" class="button-red margin-lr-xs" content="删除" @click="deleteBacDrugTestResult" :disabled="resultIsDisabled()"></vxe-button>
                <vxe-button type="text" class="button-red margin-lr-xs" class-name="margin-lr-xs" content="全部删除" @click="deleteAll" :disabled="resultIsDisabled()"></vxe-button>
              </template>
            </vxe-toolbar>
            <div style="height: calc(100% - 45px)">
              <vxe-table ref="bacDrugTestResultRef" height="auto" border show-overflow :header-cell-style="setBacDrugTestResultHeaderCellStyle" :cell-style="bacRptResultCellStyle" :data="bacDrugTestResult" :row-config="{ isCurrent: true }" :column-config="{ resizable: true }" :edit-config="{ trigger: 'click', mode: 'cell', showIcon: false, enabled: !resultIsDisabled() }" :scroll-y="{ enabled:true }" @edit-closed="bacDrugTestResultEditClose" :menu-config="tableMenuTop" @menu-click="contextMenuClickEvent" :row-style="rowStyle">
                <vxe-column type="seq" width="30"></vxe-column>
                <vxe-column field="isReport" title="报告" align="center" :edit-render="{}" width="30">
                  <template #edit="{ row,rowIndex }">
                    <vxe-checkbox v-model="row.isReport" :checked-value="1" :unchecked-value="0" @change="drugTestResultIsReportChange(row,rowIndex)"></vxe-checkbox>
                  </template>
                  <template #default="{ row }">
                    <vxe-checkbox v-model="row.isReport" :checked-value="1" :unchecked-value="0"></vxe-checkbox>
                  </template>
                </vxe-column>
                <vxe-column field="antRecomGroupId" title="分组" :edit-render="{ autofocus: '.vxe-input--inner' }" width="30px">
                  <template #default="{ row }">
                    <span>{{ row.antRecomGroupId }}</span>
                  </template>
                  <template #edit="{ row }">
                    <vxe-input v-model="row.antRecomGroupId" type="text"></vxe-input>
                  </template>
                </vxe-column>
                <vxe-column field="antNo" title="" width="35"></vxe-column>
                <vxe-column field="antNa" title="抗生素" :edit-render="{ autofocus: '.vxe-input--inner' }" width="110">
                  <template #default="{ row }">
                    <span>{{ row.antNa }}</span>
                  </template>
                  <template #edit="{ row, rowIndex }">
                    <VxePulldownSelectionByDictType :isChild="true" :childIndex="rowIndex" :isPage="false" :displayTexts="['antName']" :displayTextObj="row.antNa ? row.antNa : ''" :tableColumn="[
                        { title: '#', type: 'seq', width: '30' },
                        { title: '抗生素编码', field: 'antCode' },
                        { title: '抗生素名称', field: 'antName' }
                      ]" :aimKeys="[
                        { formKey: 'antNo', rowKey: 'antCode' },
                        { formKey: 'antNa', rowKey: 'antName' },
                        { formKey: 'potency', rowKey: 'verificationPrice' }
                      ]" :url="'/lis/bacAntibioticsDict/findAntDictList'" :dictTypeCode="'antClass'" @confirmClick="bacDrugResultConfirmClick" :isShowQuickCondition="false" />
                  </template>
                </vxe-column>
                <vxe-column field="potency" title="效价" width="50"></vxe-column>
                <vxe-column field="drugTestMethNa" title="方法" :edit-render="{ autofocus: '.vxe-input--inner' }" width="45">
                  <template #edit="{ row, rowIndex }">
                    <VxePulldownSelectionWithNa style="width: 100%" :isChild="true" :childIndex="rowIndex" :url="'/lis/bac/base/ast-test-mth/dict/findBacAstTestMthDictList'" @confirmClick="antTestMthSelectChange" :tableColumn="[
                        { type: 'seq', title: '#', width: '30px' },
                        { field: 'code', title: '名称' },
                        { field: 'name', title: '编码' }
                      ]" :aimKeys="[
                        { aimKey: 'drugMthNo', rowKey: 'code' },
                        { aimKey: 'drugTestMethNa', rowKey: 'name' }
                      ]" :displayTexts="['name']" :displayTextObj="row.drugTestMethNa ? row.drugTestMethNa : ''" />
                  </template>
                </vxe-column>
                <vxe-column field="testResult" title="结果" :edit-render="{ autofocus: '.vxe-input--inner' }" width="60">
                  <template #edit="{ row , rowIndex}">
                    <vxe-input v-model="row.testResult" type="text" placeholder="请输入结果" @keyup="keyupEvent5(row, rowIndex, $event)"></vxe-input>
                  </template>
                </vxe-column>
                <vxe-column field="interpNa" title="敏感性" :edit-render="{ autofocus: '.vxe-input--inner' }" width="50">
                  <template #edit="{ row, rowIndex }">
                    <VxePulldownSelectionWithNa style="width: 100%" :isChild="true" :childIndex="rowIndex" :url="'/lis/bac/base/interpretation-code/dict/findBacInterpretationCodeDictList'" @confirmClick="antTestMthSelectChange" :tableColumn="[
                        { type: 'seq', title: '#', width: '30px' },
                        { field: 'code', title: '名称' },
                        { field: 'name', title: '编码' }
                      ]" :aimKeys="[
                        { aimKey: 'sensitiveNo', rowKey: 'code' },
                        { aimKey: 'interpNa', rowKey: 'name' },
                        { aimKey: 'interpDisplayColor', rowKey: 'displayColor' }
                      ]" :displayTexts="['name']" :displayTextObj="row.interpNa ? row.interpNa : ''" />
                  </template>
                </vxe-column>
                <vxe-column field="breakPoint" title="折点" :edit-render="{ autofocus: '.vxe-input--inner' }" width="100">
                  <template #title>
                    <span class="text-blod">折点</span>
                  </template>
                  <template #default="{ row }">
                    <span class="preserve-format">{{ row.breakPoint }}</span>
                  </template>
                  <template #edit="{ row }">
                    <vxe-input v-model="row.breakPoint" class="preserve-format" type="text" placeholder="请输入折点"></vxe-input>
                  </template>
                </vxe-column>
                <vxe-column field="guideline" title="指南" width="80" header-align="left">
                  <template #default="{ row,rowIndex }">
                    <span v-if="row.guideline==='AUser-defined'" :class="labMainInfoObj.isChk!==2?'text-blue':''" @click="SelfBreakpointEditEvent({row:row,rowIndex:rowIndex})">自定义</span>
                    <span v-else>{{row.guideline}}</span>
                  </template>
                </vxe-column>
                <vxe-column field="isNaturlResis" title="天然耐药" align="center" :edit-render="{}" width="60">
                  <template #edit="{ row }">
                    <vxe-checkbox v-model="row.isNaturlResis" :checked-value="1" :unchecked-value="0"></vxe-checkbox>
                  </template>
                  <template #default="{ row }">
                    <vxe-checkbox v-model="row.isNaturlResis" :checked-value="1" :unchecked-value="0"></vxe-checkbox>
                  </template>
                </vxe-column>
                <vxe-column field="r" title="耐药" :edit-render="{ autofocus: '.vxe-input--inner' }" width="40">
                  <template #edit="{ row }">
                    <vxe-input v-model="row.r" type="text" placeholder="请输入耐药"></vxe-input>
                  </template>
                </vxe-column>
                <vxe-column field="i" title="中介" :edit-render="{ autofocus: '.vxe-input--inner' }" width="100">
                  <template #edit="{ row }">
                    <vxe-input v-model="row.i" type="text" placeholder="请输入中介"></vxe-input>
                  </template>
                </vxe-column>
                <vxe-column field="sdd" title="SSD" :edit-render="{ autofocus: '.vxe-input--inner' }" width="100">
                  <template #edit="{ row }">
                    <vxe-input v-model="row.sdd" type="text" placeholder="请输入SSD"></vxe-input>
                  </template>
                </vxe-column>
                <vxe-column field="s" title="敏感" :edit-render="{ autofocus: '.vxe-input--inner' }" width="40">
                  <template #edit="{ row }">
                    <vxe-input v-model="row.s" type="text" placeholder="请输入敏感"></vxe-input>
                  </template>
                </vxe-column>
                <vxe-column field="ecoff" title="流行病学界值" :edit-render="{ autofocus: '.vxe-input--inner' }" width="110">
                  <template #edit="{ row }">
                    <vxe-input v-model="row.ecoff" type="text" placeholder="请输入流行病学界值"></vxe-input>
                  </template>
                </vxe-column>
                <vxe-column field="whonetTest" title="WhonetTest" width="80" header-align="left"></vxe-column>
                <vxe-column field="breakPointRef" title="折点范围" :edit-render="{ autofocus: '.vxe-input--inner' }" width="120">
                  <template #edit="{ row }">
                    <vxe-input v-model="row.breakPointRef" type="text" placeholder="请输入折点范围"></vxe-input>
                  </template>
                </vxe-column>

                <vxe-column field="year" title="年" width="30" header-align="left"></vxe-column>
                <!-- <vxe-column field="germCodeType" title="微生物代码类型" width="110" header-align="left"></vxe-column> -->
                <vxe-column field="germNo" title="微生物代码" width="65" header-align="left"></vxe-column>
                <vxe-column field="breakPointType" title="折点类型" width="60" header-align="left"></vxe-column>
                <vxe-column field="host" title="宿主" width="50" header-align="left"></vxe-column>
                <vxe-column field="infeSite" title="感染部位" width="60" header-align="left"></vxe-column>
                <vxe-column field="refTable" title="参考表" width="60" header-align="left"></vxe-column>
                <vxe-column field="refTableSeq" title="参考表序号" width="70" header-align="left"></vxe-column>
                <vxe-column field="germMachineNo" title="仪器" width="70" header-align="left"></vxe-column>
                <vxe-column field="interpretaionNo" title="仪器敏感性" width="70" header-align="left"></vxe-column>
                <vxe-column field="sensitiveFrom" title="敏感规则" width="70" header-align="left"></vxe-column>
                <vxe-column field="breakPointId" title="折点编号" width="140" header-align="left"></vxe-column>
              </vxe-table>
            </div>
          </Pane>
        </Splitpanes>
      </Pane>
      <Pane :size="paneBottomSize">
        <BacHistories ref="BacHistoriesRef" @retrieve="retrieveBak" />
      </Pane>
    </Splitpanes>
    <BacProcessRecords ref="BacProcessRecordsRef" v-if="activeName === 'second'" :businessType="'node3'" />
    <Cost ref="costRef" v-show="activeName === 'fourth'" />
    <AddCost ref="addCostRef" v-show="activeName === 'five'" @getAddFeeCnt="getAddFeeCnt" />
    <!-- 危机值上报 -->
    <BacCriticalReport ref="criticalReportRef" @treatFinish="alarmTreatFinish" />

    <RptResultBacForm ref="RptResultBacFormRef" @confirmSave="bacTestResultConfirmSave" />
    <!-- 自定义折点录入 -->
    <BacSelfBreakpointForm ref="BacSelfBreakpointFormRef" @confirmSave="confirmSaveCallback" />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, getCurrentInstance, defineProps, onMounted } from 'vue';
import { Splitpanes, Pane } from 'splitpanes';
import { LabMainInfoBacBtns } from '../LabMainInfoBacUtils';
import { formatDateTime, IsEmpty } from '@/utils/common';
import VxePulldownSelectionByDictType from '@/components/VxePulldownSelectionByDictType.vue';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import { VXETable, VxeFormPropTypes, VxeFormInstance } from 'vxe-table';
import { AppStore } from '@/stores/store';
import { SysOptions } from '@/stores/sysoptions';
import VxePulldownSelectionWithNa from '@/components/VxePulldownSelectionWithNa.vue';
import BacProcessRecords from './BacProcessRecords.vue';
import BacHistories from './BacHistories.vue';
import RptResultBacForm from './RptResultBacForm.vue';
import Cost from './Cost.vue';
import AddCost from './AddCost.vue';
import BacCriticalReport from '@/views/lab_sys/bac_bus/components/BacCriticalReport.vue'; //危急值上报
import BacSelfBreakpointForm from './BacSelfBreakpointForm.vue';
import { saveProcessLogs } from '@/utils/BacProcessLogHelper'; /* 自定义折点录入 */
import XEClipboard from 'xe-clipboard';

defineExpose({
  initPage,
  initTestList,
  drugResultTempLdateQuickInsert /**药敏模板快速输入 */
});

const $this = {} as any;
const storeObj = AppStore();
const sysoptionObj = SysOptions(); //系统参数状态管理对象
let { proxy }: any = getCurrentInstance();
const labmaininfobacbtns = ref(LabMainInfoBacBtns().filter((item) => item.content !== '初级报告'));
const rptResultBacRef = ref(null); /**细菌结果列表对象 */
const bacDrugTestResultRef = ref(null); /**药敏结果列表对象 */
const BacProcessRecordsRef = ref(null); /**过程记录对象 */
const BacHistoriesRef = ref(null); /**历史结果组件对象 */
const RptResultBacFormRef = ref(null); /**细菌结果弹窗输入组件对象 */
let costRef: any = ref(null); //费用传值
let addCostRef: any = ref(null); //补费传值
let criticalReportRef: any = ref(null); //危急值上报
let stepNodeObj: any = reactive({}); /**当前选中流程节点对象 */
const BacSelfBreakpointFormRef = ref(); /* 自定义折点录入表单对象 */
const props = defineProps({
  tabs: {
    type: Array,
    default: reactive([
      {
        title: 'Step 1',
        iconSuccess: null,
        isValid: true
      },
      {
        title: 'Step 2',
        iconSuccess: null,
        isValid: true
      },
      {
        title: 'Step 3',
        iconSuccess: null,
        isValid: true
      }
    ])
  }
});

let isDescOptionResultFlag = ref(false); /**是否描述性结果 */
let labMainInfoObj: any = reactive({}); /**检验记录当前选中对象 */
let rptResultBacObj: any = reactive({}); /**细菌检验结果 */
let wkFlwNodeObj: any = reactive({}); /**工作流程节点对象 */
let rptResultBac: any[] = reactive([]); /**细菌检测结果列表 */
let bacDrugTestResult: any[] = reactive([]); /**细菌药敏检测结果 */
let form: any = reactive({
  autocalc: false
});
let activeName = ref('first');
let paneTopSize = ref(78);
let paneCenterSize = ref(40);
let paneBottomSize = ref(22);
let bacPanelSize = ref(20); /**细菌结果面板宽度 */
let drugPanelSize = ref(80); /**药敏结果面板宽度 */
let curRptResultBac: any = reactive({}); /**细菌鉴定结果列表行选中 */
let curSelectBacResultIndex = ref(0);

//#region  计算属性
/**是否关闭初审按钮 */
let isVisiableFChkBtn = computed(() => {
  const a = sysoptionObj.globalOptions.filter((p: any) => p.field === 'ishidefirstchk');
  if (a && a.length > 0 && a[0] && !IsEmpty(a[0].value)) {
    return IsEmpty(a[0].value) ? false : a[0].value === '1' || a[0].value === 1 ? true : false;
  }
  return false;
});
/**病历按钮显示文字(等于-时隐藏) */
let dzblBtnText = computed(() => {
  const a = sysoptionObj.globalOptions.filter((p: any) => p.field === 'blbtntxt');
  if (a && a.length > 0 && a[0] && !IsEmpty(a[0].value)) {
    return IsEmpty(a[0].value) ? '' : a[0].value === '-' ? '' : a[0].value;
  }
  return '';
});
/**历史结果高度 */
let bacHistoriesPanelHeight = computed(() => {
  let winh = window.innerHeight;
  let a = (200 / winh) * 100;
  return a;
});
/**细菌卡片宽度 */
let bacPanelWidth = computed(() => {
  let winw = window.innerWidth;
  return `${(winw * bacPanelSize.value) / 100}px`;
});
//#endregion

//#region  生命周期函数
onMounted(() => {
  //todo
});
//#endregion

/**初始化界面 */
function initPage(mainInfoRow: any) {
  Object.assign(labMainInfoObj, mainInfoRow);
  findRptResultBac();
  getBacHistories();
  getInstrGermResultInit();
}
function getInstrGermResultInit() {
  BacHistoriesRef.value?.findInstrGermResultInit(labMainInfoObj);
}

//历史回顾传值
function getBacHistories() {
  BacHistoriesRef.value?.init(labMainInfoObj, 'result');
}

function tabHandleClick(tab) {
  if (tab.paneName === 'second') {
    setTimeout(() => {
      BacProcessRecordsRef.value?.initRecords(labMainInfoObj, stepNodeObj);
    }, 200);
  } else if (tab.paneName === 'fourth') {
    costRef.value.getreqDetail(labMainInfoObj);
  } else if (tab.paneName === 'five') {
    addCostRef.value.getreqDetail(labMainInfoObj);
  }
}

// 接收父组件传值
function initTestList(repData: any, isCbUptMainInfo = true) {
  if (IsEmpty(repData) || !repData) {
    resultList.length = 0;
    return;
  }
  Object.assign(labMainInfoObj, repData);
  findRptResultBac();
}

/**检验记录 */
function actionCLick(item) {
  proxy.$emit('actionBtnsClick', item);
}

/**功能按钮事件 */
function actionEvent(m) {
  if (m.event === 'previewRpt' || m.event === 'previewPrint' || m.event === 'prelReport') {
    proxy.$emit('actionBtnsClick', m);
    return;
  }
  $this[m.event]();
}

/**查询细菌检测结果 */
function findRptResultBac() {
  console.log('刷新细菌============');

  rptResultBac.length = 0;
  bacDrugTestResult.length = 0;
  if (IsEmpty(labMainInfoObj.rptGroup) || IsEmpty(labMainInfoObj.sampleda) || IsEmpty(labMainInfoObj.sampleNo)) {
    return;
  }

  const url = '/api/bac/bac-test-result/findBacTestResultList';
  let data = { rptGroup: labMainInfoObj.rptGroup, sampleda: labMainInfoObj.sampleda + ' 00:00:00', sampleNo: labMainInfoObj.sampleNo } as any;
  // if (!IsEmpty(wkFlwNodeObj.id)) {
  //   data['wkFlwId'] = wkFlwNodeObj.workFlowId;
  //   data['wkFlwNodeId'] = wkFlwNodeObj.id;
  // }

  proxy.$http
    .get(url, { params: data })
    .then((res: any) => {
      if (res && res.data && res.data.length >= 0) {
        rptResultBac.length = 0;
        Object.assign(rptResultBac, res.data);
        //rptResultBacRef.value?.setCurrentRow(res.data[0]);
        curSelectBacResultIndex.value = curSelectBacResultIndex.value > res.data.length ? 0 : curSelectBacResultIndex.value;
        Object.assign(curRptResultBac, rptResultBac[curSelectBacResultIndex.value]);
        findBacDrugTestResult(rptResultBac[curSelectBacResultIndex.value]);
      }
    })
    .catch((err: any) => {});
}
/**危急值**/
$this['openRptCriticalValue'] = () => {
  criticalReportRef.value?.criticaReportData(labMainInfoObj);
};

//发布细菌结果
$this['publishTestResult'] = async () => {
  if (rptResultBac.length == 0) {
    VxeMessage('没有细菌记录，发布细菌报告失败', VxeNotifyType.warning);
    return;
  }

  const type = await VXETable.modal.confirm('确定要发布细菌报告吗？');
  if (type === 'confirm') {
    console.log(rptResultBac);
    const datas = [];
    const data = {
      rptGroup: rptResultBac[0].rptGroup,
      sampleda: rptResultBac[0].sampleda + ' 00:00:00',
      sampleNo: rptResultBac[0].sampleNo,
      testFlowNo: labMainInfoObj.testFlowNo,
      testNodeNo: labMainInfoObj.nodeNo
    };
    datas.push(data);
    const url = '/api/bac/bac-publis-first-report/publisGermReport';
    proxy.$http.post(url, datas).then((res: any) => {
      VxeMessage('发布成功', VxeNotifyType.success);
      try {
        const a = localStorage.getItem('userInfo');
        const b = JSON.parse(a);
        const processLogData = {
          strainId: null,
          strainNo: null,
          strainName: null,
          maininfoId: labMainInfoObj.id,
          wkFlwId: null,
          wkFlwNodeId: null,
          rptGroup: labMainInfoObj.rptGroup,
          sampleda: formatDateTime(labMainInfoObj.sampleda, 'yyyy-MM-dd 00:00:00'),
          sampleNo: labMainInfoObj.sampleNo,
          testFlowNo: labMainInfoObj.testFlowNo,
          testNodeNo: labMainInfoObj.nodeNo,
          content: `【${formatDateTime(new Date(), 'yyyy-MM-dd hh:mm:ss')}】操作人:【${IsEmpty(b.realname) ? '' : b.realname}】发布细菌报告\n`,
          operatorDoctor: IsEmpty(b.username) ? '' : b.username
        };
        saveProcessLogs(processLogData);
      } catch (error) {}
    });
  }
};

/**危急值处理完成 */
function alarmTreatFinish(data) {
  /* if (alarmReportBeforeChk.value && !chkBeforePrint.value) {
     $this['chkMainInfo']();
   }
   if (alarmReportBeforeChk.value && chkBeforePrint.value) {
     $this['previewPrint']();
   }*/
  try {
    const a = localStorage.getItem('userInfo');
    const b = JSON.parse(a);

    const cntStrArr = [`【${formatDateTime(new Date(), 'yyyy-MM-dd hh:mm:ss')}】操作人:【${IsEmpty(b.realname) ? '' : b.realname}】发布危急值\n`];
    data.forEach((itm) => {
      if (itm.criItem) {
        if (!IsEmpty(itm.criItem.isolateNum)) {
          cntStrArr.push(`【第${itm.criItem.isolateNum}珠菌】`);
        }
        if (!IsEmpty(itm.criItem.criticalItemType)) {
          if (itm.criItem.criticalItemType === 3) {
            cntStrArr.push(`危急值类型:细菌危急值`);
          } else if (itm.criItem.criticalItemType === 4) {
            cntStrArr.push(`危急值类型:药敏危急值`);
          } else {
            cntStrArr.push(`危急值类型:危急值`);
          }
        }
        if (!IsEmpty(itm.criItem.germNa)) {
          cntStrArr.push(`鉴定结果: ${itm.criItem.germNa}`);
        }
        if (!IsEmpty(itm.criItem.testResult)) {
          cntStrArr.push(`结果描述: ${itm.criItem.testResult}`);
        }
        if (!IsEmpty(itm.criItem.resiPhenNa)) {
          cntStrArr.push(`耐药表型: ${itm.criItem.resiPhenNa}`);
        }
        if (!IsEmpty(itm.criItem.urinColoCount)) {
          cntStrArr.push(`尿细菌计数: ${itm.criItem.urinColoCount}`);
        }
        if (!IsEmpty(itm.criItem.infeSiteNa)) {
          cntStrArr.push(`感染部位: ${itm.criItem.infeSiteNa}`);
        }
        if (!IsEmpty(itm.criItem.alarmText)) {
          cntStrArr.push(`危急值描述: ${itm.criItem.alarmText}`);
        }
      }
      if (itm.criData) {
        if (!IsEmpty(itm.criData.notifyPersonNa)) {
          cntStrArr.push(`通知医师:${itm.criData.notifyPersonNa}`);
        }
        if (!IsEmpty(itm.criData.reportPersonNa)) {
          cntStrArr.push(`发布人:${itm.criData.reportPersonNa}`);
        }
        if (!IsEmpty(itm.criData.notificationTypeNa)) {
          cntStrArr.push(`通知方式:${itm.criData.notificationTypeNa}`);
        }
        if (!IsEmpty(itm.criData.remark)) {
          cntStrArr.push(`备注:${itm.criData.remark}`);
        }
      }
      if (cntStrArr && cntStrArr.length > 0) {
        cntStrArr.push(`\n`);
      }
    });

    const cntStr = cntStrArr
      .filter(Boolean) // 过滤掉空字符串
      .join('\n');

    courseRecord(`${cntStr}`, curRptResultBac);
  } catch (error) {}
}

/**插入细菌阳性检测结果 */
function findRptResultBacYangX() {
  rptResultBac.length = 0;
  bacDrugTestResult.length = 0;

  if (IsEmpty(labMainInfoObj.rptGroup) || IsEmpty(labMainInfoObj.sampleda) || IsEmpty(labMainInfoObj.sampleNo)) {
    return;
  }

  const url = '/api/bac/bac-test-result/findBacTestResultList';
  let data = { rptGroup: labMainInfoObj.rptGroup, sampleda: labMainInfoObj.sampleda + ' 00:00:00', sampleNo: labMainInfoObj.sampleNo } as any;

  proxy.$http
    .get(url, { params: data })
    .then((res: any) => {
      if (res && res.data && res.data.length >= 0) {
        rptResultBac.length = 0;
        Object.assign(rptResultBac, res.data);
        curSelectBacResultIndex.value = 0;
        findBacDrugTestResult(rptResultBac[0]);
      }
    })
    .catch((err: any) => {});
}

/**查询细菌检测结果 */
function findBacDrugTestResult(rptResultBac) {
  bacDrugTestResult.length = 0;
  if (IsEmpty(labMainInfoObj.rptGroup) || IsEmpty(labMainInfoObj.sampleda) || IsEmpty(labMainInfoObj.sampleNo)) {
    return;
  }
  const url = '/api/bac/bac-drug-test-result/findBacDrugTestResultList';
  let data = { rptGroup: labMainInfoObj.rptGroup, sampleda: labMainInfoObj.sampleda + ' 00:00:00', sampleNo: labMainInfoObj.sampleNo, isolateNum: rptResultBac.isolateNum, testFlowNo: labMainInfoObj.testFlowNo, testNodeNo: labMainInfoObj.nodeNo, germNo: rptResultBac.germNo } as any;
  proxy.$http
    .get(url, { params: data })
    .then((res: any) => {
      if (res && res.data && res.data.length >= 0) {
        bacDrugTestResult.length = 0;
        Object.assign(bacDrugTestResult, res.data);
        bacDrugTestResult.value?.setCurrentRow(res.data[0]);
      }
    })
    .catch((err: any) => {});
}
/**设置表头单元格样式 */
function setBacDrugTestResultHeaderCellStyle({ column }) {
  if (column.field === 'r' || column.field === 'i' || column.field === 'sdd' || column.field === 's' || column.field === 'ecoff' || column.field === 'whonetTest' || column.field === 'breakPointRef' || column.field === 'guideline' || column.field === 'year' || column.field === 'germCodeType' || column.field === 'orgCodeType' || column.field === 'germNo' || column.field === 'breakPointType' || column.field === 'host' || column.field === 'infeSite' || column.field === 'refTable' || column.field === 'refTableSeq' || column.field === 'breakPointId') {
    return { fontWeight: 300 };
  }
}
/** 细菌检测结果列表单元格样式*/
function setRptResultBacCellStyle({ row, column }) {
  if (column.field === 'wkFlwId') {
    return { backgroundColor: '#409eff', height: '100%' };
  }
  return null;
}
/**判断使用哪个结果选择组件 */
function validateWitchResultComp(row) {
  let res = false;
  if ((IsEmpty(row.id) && IsEmpty(row.germNo)) || (!IsEmpty(row.id) && !isDescOptionResultFlag.value)) {
    res = true;
  }
  return res;
}
/**刷新细菌泪飙 */
$this['refreshRptResultBac'] = async () => {
  findRptResultBac();
};
/**审核 */
$this['chkMainInfo'] = async () => {};
/**新增鉴定结果 */
$this['insertRptResultBac'] = (isDescOptionsResult = false) => {
  isDescOptionResultFlag.value = isDescOptionsResult;
  if (IsEmpty(labMainInfoObj.sampleda) || IsEmpty(labMainInfoObj.rptGroup) || IsEmpty(labMainInfoObj.sampleNo) || IsEmpty(labMainInfoObj.id)) {
    VxeMessage('请先选中上机记录', VxeNotifyType.warning);
    return;
  }
  RptResultBacFormRef.value?.showModal(labMainInfoObj, false, rptResultBac && rptResultBac.length > 0 ? `${rptResultBac.length + 1}` : '1');
};
/**新增鉴定结果 */
$this['insertRptResultBacYangX'] = (isDescOptionsResult = false) => {
  isDescOptionResultFlag.value = isDescOptionsResult;
  if (IsEmpty(labMainInfoObj.sampleda) || IsEmpty(labMainInfoObj.rptGroup) || IsEmpty(labMainInfoObj.sampleNo) || IsEmpty(labMainInfoObj.id)) {
    VxeMessage('请先选中上机记录', VxeNotifyType.warning);
    return;
  }
  RptResultBacFormRef.value?.showModal(labMainInfoObj, true, rptResultBac && rptResultBac.length > 0 ? `${rptResultBac.length + 1}` : '1');
};
/**新增抗生素结果 */
async function insertBacDrugTestResult() {
  if (IsEmpty(curRptResultBac.id)) {
    VxeMessage('请先添加细菌结果', VxeNotifyType.error);
    return;
  }
  let row = {
    id: '',
    bacTestResultId: curRptResultBac.id,
    isReport: 0,
    wkFlwId: '',
    sampleda: formatDateTime(labMainInfoObj.sampleda, 'yyyy-MM-dd' + ' 00:00:00'),
    rptGroup: labMainInfoObj.rptGroup,
    sampleNo: labMainInfoObj.sampleNo,
    maininfoId: labMainInfoObj.id,
    antRecomGroupNa: '',
    antNo: '',
    antNa: '',
    potency: '',
    drugTestMethNa: '',
    testResult: '',
    interpNa: '',
    sensitiveNo: '',
    drugMthNo: '',
    breakPoint: '',
    isNaturlResis: 0,
    r: '',
    i: '',
    sdd: '',
    s: '',
    ecoff: '',
    whonetTest: '',
    breakPointRef: '',
    guideline: '',
    year: '',
    germCodeType: '',
    germNo: curRptResultBac.germNo,
    breakPointType: '',
    host: '',
    infeSite: '',
    refTable: '',
    refTableSeq: '',
    breakPointId: '',
    isolateNum: null,
    germNa: curRptResultBac.germNa,
    resiPhenNa: '',
    urinColoCount: null,
    infeSiteNa: '',
    dataFrom: '2' /* 数据来源  1 仪器上传    2  手工添加  3 开始仪器上传 后来手工修改 */
  };
  bacDrugTestResult.push(row);
  await bacDrugTestResultRef.value?.setCurrentRow(row);
  await bacDrugTestResultRef.value?.setEditCell(row, 'antNa');
  setTimeout(() => {
    bacDrugTestResultRef.value?.scrollToRow(row);
  }, 100);
}
/**微生物结果选择确认事件 */
function rptResultBacConfirmClick(e) {
  if (e.isChild) {
    e.aimKeys.forEach((m) => {
      rptResultBac[e.childIndex][m.formKey] = e.row[m.rowKey];
    });
  }
}
/**描述性结果选择确认 */
function SelectRowClick(e) {
  if (e.isChild) {
    e.aimKeys.forEach((m) => {
      rptResultBac[e.childIndex][m.aimKey] = e.row[m.rowKey];
    });
  }
}
/**药敏测试方法选择改变 */
function antTestMthSelectChange(e) {
  if (e.isChild) {
    e.aimKeys.forEach((m) => {
      bacDrugTestResult[e.childIndex][m.aimKey] = e.row[m.rowKey];
    });
  }
}
/**抗生素结果确认事件 */
function bacDrugResultConfirmClick(e) {
  if (e.isChild) {
    e.aimKeys.forEach((m) => {
      bacDrugTestResult[e.childIndex][m.formKey] = e.row[m.rowKey];
    });
    if (IsEmpty(bacDrugTestResult[e.childIndex].id)) {
      if (!IsEmpty(bacDrugTestResult[e.childIndex - 1])) {
        bacDrugTestResult[e.childIndex].seq = Number(bacDrugTestResult[e.childIndex - 1].seq) + 1;
      } else {
        bacDrugTestResult[e.childIndex].seq = 1;
      }
    }
  }
}
/**细菌结果列表关闭编辑状态 */
function rptResultBacEditClosed({ row, rowIndex, $rowIndex, column, columnIndex, $columnIndex }) {
  row.testFlowNo = labMainInfoObj.testFlowNo;
  row.testNodeNo = labMainInfoObj.nodeNo;
  row.sampleda = labMainInfoObj.sampleda;
  row.resiPhenId = IsEmpty(row.resiPhenId) ? '' : row.resiPhenId;
  row.resiPhenNa = IsEmpty(row.resiPhenNa) ? '' : row.resiPhenNa;
  row.resiPhenNo = IsEmpty(row.resiPhenNo) ? '' : row.resiPhenNo;
  row.strainNo = IsEmpty(row.strainNo) ? '' : row.strainNo;
  row.urinColoCount = IsEmpty(row.urinColoCount) ? '' : row.urinColoCount;
  row.infeSiteNo = IsEmpty(row.infeSiteNo) ? '' : row.infeSiteNo;
  row.infeSiteNa = IsEmpty(row.infeSiteNa) ? '' : row.infeSiteNa;
  row.testResult = IsEmpty(row.testResult) ? '' : row.testResult;
  let url = `/api/bac/bac-test-result/${row && !IsEmpty(row.id) ? 'updateBacTestResult' : 'addBacTestResult'}`;
  console.log('row===...>>', row);

  proxy.$http
    .post(url, row)
    .then((res: any) => {
      if (rptResultBac && rptResultBac.length > 0 && rptResultBac[rowIndex] && rowIndex && res && res.data) {
        Object.assign(rptResultBac[rowIndex], res.data);
      }

      if (res && res.status && res.status.code === 1 && res.data) {
        /* try {
          const a = localStorage.getItem('userInfo');
          const b = JSON.parse(a);
          let aore = '';
          if (row && !IsEmpty(row.id)) {
            aore = '修改';
          } else {
            aore = '添加';
          }
          const contentSrr = [`【${formatDateTime(new Date(), 'yyyy-MM-dd hh:mm:ss')}】操作人:【${IsEmpty(b.realname) ? '' : b.realname}】${aore}鉴定结果\n`, !IsEmpty(row.germNa) ? `结果:  ${row.germNa}   序号:${row.isolateNum}` : '', !IsEmpty(row.urinColoCount) ? `菌落计数:  ${row.urinColoCount}` : '', !IsEmpty(row.bacRate) ? `菌群比例:  ${row.bacRate}%` : '', !IsEmpty(row.resiPhenNa) ? `耐药表型:  ${row.resiPhenNa}` : '', !IsEmpty(row.infeSiteNa) ? `感染部位:  ${row.infeSiteNa}` : '', !IsEmpty(row.isContagion) ? '传染病:' + (row.isContagion ? '是' : '否') + '' : '', !IsEmpty(row.isAlarm) ? '危急值:' + (row.isAlarm ? '是' : '否') + '' : '', !IsEmpty(row.alarmText) ? `危急值描述:  ${row.alarmText}` : '', !IsEmpty(row.alarmText) ? '药敏危急值:' + (row.alarmText ? '是' : '否') + '' : '', !IsEmpty(row.drugAlarmText) ? `药敏危急值描述:  ${row.drugAlarmText}` : '', !IsEmpty(row.testResult) ? `结果描述:  ${row.testResult}` : '', !IsEmpty(row.descText) ? `专家评语:  ${row.descText}` : ''].filter(Boolean).join('\n');
          courseRecord(`${contentSrr}`, row);
        } catch (error) {}*/
        proxy.$emit('currentRow', labMainInfoObj);
      }
      findRptResultBac();
      proxy.$forceUpdate();
    })
    .catch((err: any) => {
      //ToDo
    });
}

function drugTestResultIsReportChange(row, rowIndex) {
  if (row && !IsEmpty(row.id)) {
    let url = '/api/bac/bac-drug-test-result/drugTestResultIsReportChange';
    proxy.$http
      .post(url, row)
      .then(async (res: any) => {
        if (res && res.status && res.status.code === 1) {
          Object.assign(bacDrugTestResult[rowIndex], res.data);
        }
      })
      .catch((err: any) => {
        //ToDo
      });
  }
}
/**药敏鉴定结果列表关闭编辑状态 */
function bacDrugTestResultEditClose({ row, rowIndex, $rowIndex, column, columnIndex, $columnIndex }) {
  if (!IsEmpty(column) && column.field == 'isReport') {
    //修改是否报告时不修改整体数据
    console.log('修改是否报告时不修改整体数据');
    return;
  }
  row.testFlowNo = curRptResultBac.testFlowNo;
  row.testNodeNo = curRptResultBac.testNodeNo;
  row.isolateNum = curRptResultBac.isolateNum;
  if (row && !IsEmpty(row.id) && IsEmpty(row.germNo)) {
    row.germNo = curRptResultBac.germNo;
  }
  if (IsEmpty(row.antNo)) {
    return;
  }
  //输出日志
  let aore = '';
  if (row && !IsEmpty(row.id)) {
    aore = '修改';
  } else {
    aore = '添加';
  }
  let url = `/api/bac/bac-drug-test-result/${row && !IsEmpty(row.id) ? 'updateBacDrugTestResult' : 'addBacDrugTestResult'}`;
  proxy.$http
    .post(url, row)
    .then(async (res: any) => {
      Object.assign(bacDrugTestResult[rowIndex], res.data);
      if (res && res.status && res.status.code === 1) {
        /*   try {
          const a = localStorage.getItem('userInfo');
          const b = JSON.parse(a);
          const contentSrr = [`【${formatDateTime(new Date(), 'yyyy-MM-dd hh:mm:ss')}】操作人:【${IsEmpty(b.realname) ? '' : b.realname}】${aore}抗生素结果\n`, !IsEmpty(row.germNa) ? `细菌:  ${curRptResultBac.germNa}   序号:${row.isolateNum}` : '', !IsEmpty(row.antNa) ? `抗生素:  ${row.antNa}` : '', !IsEmpty(row.drugTestMethNa) ? `测试方法:  ${row.drugTestMethNa}` : '', !IsEmpty(row.potency) ? `效价:  ${row.potency}` : '', !IsEmpty(row.testResult) ? `结果:  ${row.testResult}` : '', !IsEmpty(row.interpNa) ? `敏感性:  ${row.interpNa}` : ''].filter(Boolean).join('\n');
          courseRecord(`${contentSrr}`, curRptResultBac);
        } catch (error) {}*/
      }
      //如果是天然耐药 则不需要弹出这个提示
      //if (res && res.data && IsEmpty(res.data.sensitiveFrom)) {
      if (res && res.data && IsEmpty(res.data.breakPointId) && IsEmpty(res.data.guideline) && IsEmpty(res.data.year) && !IsEmpty(res.data.testResult) && !IsEmpty(res.data.antNo) && !IsEmpty(res.data.drugMthNo) && !IsEmpty(res.data.germNo)) {
        const type = await VXETable.modal.confirm('未计算出折点信息,是否将选择存储为自定义折点?', '提示', { mask: false });
        if (type === 'confirm') {
          let obj = {};
          Object.assign(obj, res.data);
          obj[`whonetOrgName`] = curRptResultBac.germNa;
          obj[`testMethod`] = row.drugMthNo;
          obj[`testMethodNa`] = row.drugTestMethNa;
          BacSelfBreakpointFormRef.value.showModal(obj, res.data.id);
        }
      }
      //}
    })
    .catch((err: any) => {
      //ToDo
    });
}
/* 自定义折点保存完成，重新计算该抗生素的折点信息 */
function confirmSaveCallback(e) {
  bacDrugTestResult.forEach((m, i) => {
    if (m.id === e.id) {
      bacDrugTestResultEditClose({ row: m, rowIndex: i });
    }
  });
}
/**细菌列表行选择改变 */
function rptResultBacSelectChange({ row }) {
  Object.assign(curRptResultBac, row);
  bacDrugTestResult.length = 0;
  findBacDrugTestResult(curRptResultBac);
}
/**药敏鉴定结果 刷新按钮刷新 */
function bacDrugTestResultRefresh() {
  findBacDrugTestResult(curRptResultBac);
}
/**删除细菌鉴定结果 */
async function deleterptResultBac(index) {
  const row = {} as any; //curRptResultBac;//rptResultBacRef.value?.getCurrentRecord();
  Object.assign(row, curRptResultBac);
  if (IsEmpty(row) || IsEmpty(row.id)) {
    VxeMessage('请先选中要删除的行', VxeNotifyType.warning);
    return;
  }
  const type = await VXETable.modal.confirm('确定删除选中记录?'); /*不能改el  $confirm 回车事件冒泡你*/
  if (type === 'confirm') {
    let url = `/api/bac/bac-test-result/deleteBacTestResult`;
    proxy.$http
      .post(url, row)
      .then(async (res: any) => {
        if (res && res.status && !IsEmpty(res.status.code) && res.status.code === 1) {
          curSelectBacResultIndex.value = 0;
          findRptResultBac();
          VxeMessage(res.status.msg, VxeNotifyType.success);

          /*        try {
            const a = localStorage.getItem('userInfo');
            const b = JSON.parse(a);
            const contentSrr = [`【${formatDateTime(new Date(), 'yyyy-MM-dd hh:mm:ss')}】操作人:【${IsEmpty(b.realname) ? '' : b.realname}】删除鉴定结果\n`, !IsEmpty(row.germNa) ? `结果:  ${row.germNa}   序号:${row.isolateNum}` : '', !IsEmpty(row.urinColoCount) ? `菌落计数:  ${row.urinColoCount}` : '', !IsEmpty(row.bacRate) ? `菌群比例:  ${row.bacRate}%` : '', !IsEmpty(row.resiPhenNa) ? `耐药表型:  ${row.resiPhenNa}` : '', !IsEmpty(row.infeSiteNa) ? `感染部位:  ${row.infeSiteNa}` : '', !IsEmpty(row.isContagion) ? '传染病:' + (row.isContagion ? '是' : '否') + '' : '', !IsEmpty(row.isAlarm) ? '危急值:' + (row.isAlarm ? '是' : '否') + '' : '', !IsEmpty(row.alarmText) ? `危急值描述:  ${row.alarmText}` : '', !IsEmpty(row.alarmText) ? '药敏危急值:' + (row.alarmText ? '是' : '否') + '' : '', !IsEmpty(row.drugAlarmText) ? `药敏危急值描述:  ${row.drugAlarmText}` : '', !IsEmpty(row.testResult) ? `结果描述:  ${row.testResult}` : '', !IsEmpty(row.descText) ? `专家评语:  ${row.descText}` : ''].filter(Boolean).join('\n');
            courseRecord(`${contentSrr}`, row);
          } catch (error) {}*/
        } else {
          VxeMessage(res.status.msg, VxeNotifyType.error);
        }
      })
      .catch((err: any) => {
        VxeMessage('删除失败', VxeNotifyType.error);
      });
  }
}
/**删除药敏检验结果 */
async function deleteBacDrugTestResult() {
  const row = bacDrugTestResultRef.value?.getCurrentRecord();
  if (IsEmpty(row) || IsEmpty(row.id)) {
    VxeMessage('请先选中要删除的行', VxeNotifyType.warning);
    return;
  }
  const type = await VXETable.modal.confirm('确定删除选中记录?'); /*不能改el  $confirm 回车事件冒泡你*/
  if (type === 'confirm') {
    let url = `/api/bac/bac-drug-test-result/deleteBacDrugTestResult`;
    proxy.$http
      .post(url, row)
      .then(async (res: any) => {
        if (res && res.status && !IsEmpty(res.status.code) && res.status.code === 1) {
          const ci = bacDrugTestResultRef.value?.getRowIndex(row);
          await bacDrugTestResultRef.value?.remove(row);
          bacDrugTestResult.splice(ci, 1);
          VxeMessage(res.status.msg, VxeNotifyType.success);

          /*  try {
            const a = localStorage.getItem('userInfo');
            const b = JSON.parse(a);
            const contentSrr = [`【${formatDateTime(new Date(), 'yyyy-MM-dd hh:mm:ss')}】操作人:【${IsEmpty(b.realname) ? '' : b.realname}】删除抗生素\n`, !IsEmpty(curRptResultBac.germNa) ? `结果:  ${curRptResultBac.germNa}   序号:${curRptResultBac.isolateNum}` : '', !IsEmpty(row.antNa) ? `抗生素:  ${row.antNa}` : ''].filter(Boolean).join('\n');
            courseRecord(`${contentSrr}`, curRptResultBac);
          } catch (error) {}*/
        } else {
          VxeMessage(res.status.msg, VxeNotifyType.error);
        }
      })
      .catch((err: any) => {
        VxeMessage('删除失败', VxeNotifyType.error);
      });
  }
}
/**选择药敏模板 */
function insertBacDrugResultTemplate() {
  if (IsEmpty(curRptResultBac.id)) {
    VxeMessage('请先添加细菌结果', VxeNotifyType.error);
    return;
  }
  proxy.$emit('selectBacDrugResultTemplate');
}
/**药敏模板快速输入 */
function drugResultTempLdateQuickInsert(rows) {
  //rptResultBac
  const data = {
    rptGroup: labMainInfoObj.rptGroup,
    sampleda: labMainInfoObj.sampleda + ' 00:00:00',
    sampleNo: labMainInfoObj.sampleNo,
    testFlowNo: labMainInfoObj.testFlowNo,
    testNodeNo: labMainInfoObj.nodeNo,
    isolateNum: rptResultBac[curSelectBacResultIndex.value].isolateNum,
    bacDrugResultTemplates: rows,
    germNo: curRptResultBac.germNo
  };
  let url = `/api/bac/bac-drug-test-result/drugResultTemplateQuickInsert`;
  proxy.$http
    .post(url, data)
    .then(async (res: any) => {
      if (res && res.status && !IsEmpty(res.status.code) && res.status.code === 1) {
        findBacDrugTestResult(rptResultBac[curSelectBacResultIndex.value]);
        VxeMessage(res.status.msg, VxeNotifyType.success);

        /*        try {
          const a = localStorage.getItem('userInfo');
          const b = JSON.parse(a);
          const antNaStrs = rows.map((item) => item.templateNa).join('\n');
          const contentSrr = [`【${formatDateTime(new Date(), 'yyyy-MM-dd hh:mm:ss')}】操作人:【${IsEmpty(b.realname) ? '' : b.realname}】通过药敏模板添加抗生素\n`, !IsEmpty(curRptResultBac.germNa) ? `结果:  ${curRptResultBac.germNa}   序号:${rptResultBac[curSelectBacResultIndex.value].isolateNum}` : '', !IsEmpty(antNaStrs) ? `模板名称:  ${antNaStrs}` : ''].filter(Boolean).join('\n');
          courseRecord(`${contentSrr}`, curRptResultBac);
        } catch (error) {}*/
      } else {
        VxeMessage(res.status.msg, VxeNotifyType.error);
      }
    })
    .catch((err: any) => {
      VxeMessage('删除失败', VxeNotifyType.error);
    });
}
/**批量删除药敏结果 */
async function deleteAll() {
  const type = await VXETable.modal.confirm('确定全部删除记录?'); /*不能改el  $confirm 回车事件冒泡你*/
  if (type === 'confirm') {
    let url = `/api/bac/bac-drug-test-result/batchDeleteBacDrugTestResult`;
    proxy.$http
      .post(url, bacDrugTestResult)
      .then((res: any) => {
        if (res && res.status && !IsEmpty(res.status.code) && res.status.code === 1) {
          findBacDrugTestResult(curRptResultBac);
          VxeMessage(res.status.msg, VxeNotifyType.success);

          /*  try {
            const a = localStorage.getItem('userInfo');
            const b = JSON.parse(a);
            const contentSrr = [`【${formatDateTime(new Date(), 'yyyy-MM-dd hh:mm:ss')}】操作人:【${IsEmpty(b.realname) ? '' : b.realname}】删除全部抗生素\n`, !IsEmpty(curRptResultBac.germNa) ? `结果:  ${curRptResultBac.germNa}   序号:${curRptResultBac.isolateNum}` : ''].filter(Boolean).join('\n');
            courseRecord(`${contentSrr}`, curRptResultBac);
          } catch (error) {}*/
        } else {
          VxeMessage(res.status.msg, VxeNotifyType.error);
        }
      })
      .catch((err: any) => {
        VxeMessage('删除失败', VxeNotifyType.error);
      });
  }
}
/**细菌结果卡片点击事件 */
function bacResultCardClick(row, i) {
  BacHistoriesRef.value?.initGermObj(row);
  Object.assign(curRptResultBac, row);
  /* 日志输出 */
  curSelectBacResultIndex.value = i;
  findBacDrugTestResult(curRptResultBac);
}
/**细菌结果卡片修改点击事件 */
function bacTestResultEditClick(row, i) {
  bacResultCardClick(row, i);
  RptResultBacFormRef.value?.editShowModal(row, labMainInfoObj, !IsEmpty(row.id) && !IsEmpty(row.germNo) ? true : false);
}
/**细菌结果卡片删除点击事件 */
function bacTestResultDeleteClick(row, i) {
  bacResultCardClick(row, i);
  deleterptResultBac(i);
}
/**细菌结果鉴定确认保存 */
function bacTestResultConfirmSave(e) {
  rptResultBacEditClosed({ row: e, rowIndex: curSelectBacResultIndex + 1 });
}
/**抗生素列表单元格样式 */
function bacRptResultCellStyle({ row, rowIndex, $rowIndex, column, columnIndex, $columnIndex }) {
  if (column && column.field && column.field === 'interpNa') {
    if (row && !IsEmpty(row['interpDisplayColor'])) {
      return { backgroundColor: row['interpDisplayColor'] ? row['interpDisplayColor'] : '', color: row['interpDisplayColor'] ? '#fff' : '#000' };
    }
  }
}
/**判断是否审核，若审核范围ture */
function resultIsDisabled() {
  if (!IsEmpty(labMainInfoObj) && labMainInfoObj.isChk == '2') {
    return true;
  } else {
    return false;
  }
}

function keyupEvent5(row, rowIndex, e) {
  if (e.$event.keyCode === 13) {
    const isNextRow = bacDrugTestResult.length - 1 - rowIndex > 0;
    if (isNextRow) {
      const $table = proxy.$refs.bacDrugTestResultRef as any;
      if ($table) {
        $table?.setCurrentRow(bacDrugTestResult[rowIndex + 1]);
        $table?.setEditCell(bacDrugTestResult[rowIndex + 1], 'testResult');
      }
    }
  }
}

/* 自定义折点编辑 */
function SelfBreakpointEditEvent({ row, rowIndex }) {
  if (!IsEmpty(labMainInfoObj.isChk) && labMainInfoObj.isChk === 2) {
    return;
  }
  let obj = {};
  Object.assign(obj, row);
  obj[`whonetOrgName`] = curRptResultBac.germNa;
  obj[`testMethod`] = row.drugMthNo;
  obj[`testMethodNa`] = row.drugTestMethNa;
  BacSelfBreakpointFormRef.value.editShowModal(obj, row.id);
}

function retrieveBak() {
  console.log('刷新=======');
  findRptResultBac();
  //findBacDrugTestResult(curRptResultBac);
}
/* 添过程记录 */
function courseRecord(val, germResult) {
  const a = localStorage.getItem('userInfo');
  const b = JSON.parse(a);
  const row = {
    strainId: null,
    strainNo: germResult.isolateNum,
    strainName: germResult.germNa,
    maininfoId: labMainInfoObj.id,
    rptGroup: labMainInfoObj.rptGroup,
    sampleda: formatDateTime(labMainInfoObj.sampleda, 'yyyy-MM-dd 00:00:00'),
    sampleNo: labMainInfoObj.sampleNo,
    testFlowNo: germResult.testFlowNo,
    testNodeNo: germResult.testNodeNo,
    content: val,
    operatorDoctor: IsEmpty(b.username) ? '' : b.username
  };

  const url = '/bac/strainLog/addStrainLog';
  proxy.$http
    .post(url, row)
    .then((res: any) => {})
    .catch((err: any) => {});
}

function getAddFeeCnt(data) {
  proxy.$emit('getAddFeeCnt', data);
}

let tableMenuTop = reactive({
  className: 'my-menus',
  body: {
    options: [[{ code: 'copy', name: '复制内容', prefixIcon: 'vxe-icon-copy', className: 'my-copy-item' }]]
  }
});

/**待打印表格右键单机 */
function contextMenuClickEvent({ menu, row, column }) {
  switch (menu.code) {
    case 'copy':
      // 示例
      if (row && column) {
        if (XEClipboard.copy(row[column.field])) {
          VXETable.modal.message({ content: '已复制到剪贴板！', status: 'success' });
        }
      }
      break;

    default:
    //VXETable.modal.alert(`点击了 ${menu.name} 选项`)
  }
}

const rowStyle = ({ row, rowIndex }) => {
  console.log(row);
  //IsEmpty
  if (!IsEmpty(row.interpretaionNo) && row.interpretaionNo != row.sensitiveNo) {
    return {
      backgroundColor: '#ffd5d5'
    };
  }
};
</script>

<style scoped lang="scss">
@import '@/assets/css/el-tabs.scss';

#rptResultBac {
  height: calc(100%);
}

.bacRptResult-splitpanes {
  height: calc(100vh - 240px);
}

.lab-bac-test-result-tab {
  :deep(.el-tabs__header) {
    margin-bottom: 0;
  }

  :deep(.el-tabs__nav-prev) {
    line-height: 28px !important;
  }

  :deep(.el-tabs__nav-next) {
    line-height: 28px !important;
  }

  :deep(.el-tabs__content) {
    height: 0px;
    padding: 2px;
  }

  :deep(.el-tab-pane) {
    height: 0px;
  }
}

:deep(.cell-bgColor) {
  .vxe-cell {
    height: 100%;
  }
}

:deep(.bac-card) {
  cursor: pointer;

  .el-card__header {
    padding: 5px 5px;
  }

  .el-card__body {
    padding: 5px 5px;

    .bac-result-content {
      font-size: 0.8em;

      .label-des {
        font-weight: 550;
        margin-right: 2px;
      }
    }
  }

  .el-card__footer {
    padding: 5px 5px;
  }
}

.preserve-format {
  white-space: pre-wrap; /* 保留空格和换行，并支持自动换行 */
  font-family: monospace; /* 可选：使用等宽字体 */
}
</style>
